package whisper.api.gateway.frame.auth.filter.permission;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.access.ConfigAttribute;
import org.springframework.security.access.SecurityConfig;
import org.springframework.security.web.FilterInvocation;
import org.springframework.security.web.access.intercept.FilterInvocationSecurityMetadataSource;
import org.springframework.stereotype.Component;
import whisper.api.gateway.frame.auth.domain.Role;
import whisper.api.gateway.frame.auth.service.PermissionService;

import java.util.*;

/**
 * Created by JT on 2017/9/25.
 */
@Component
public class ConsumerInvocationSecurityMetadataSourceService implements FilterInvocationSecurityMetadataSource {

    @Autowired
    private PermissionService permissionService;

    @Override
    public Collection<ConfigAttribute> getAttributes(Object o) throws IllegalArgumentException {
        /**
         * 获取能够访问 URL 的角色
         */
        String url = ((FilterInvocation) o).getRequestUrl();
        String type = ((FilterInvocation) o).getRequest().getMethod();
        List<Role> roles = permissionService.findRolesByPermissionUrlAndType(url, type);

        Set roleSet = new HashSet();
        for (Role role : roles) {
            roleSet.add(new SecurityConfig(role.getCode()));
        }
        return roleSet;
    }

    @Override
    public Collection<ConfigAttribute> getAllConfigAttributes() {
        return new ArrayList<ConfigAttribute>();
    }

    @Override
    public boolean supports(Class<?> aClass) {
        return true;
    }
}
